<?php

class _F_EXTENSION_DATA_RESULT_SET_ extends _F_OBJECT_
implements IteratorAggregate, Countable {
	
	public $db;
	public $class;
	public $query;
	public $params;
	public $_f_count_ = null;
	public $_f_where_ = null;
	public $_f_order_ = null;
	public $_f_limit_ = null;
	public $_f_sql_ = null;

	public function __construct($db,$query,$params,$class) {
		$this->db = $db;
		$this->class = $class;
		$this->query = $query;
		$this->params = $params;
	}
	
	public function getIterator() {
		$stmnt = $this->db->connection->prepare($this->sql);
		if ($stmnt->execute($this->params)) {
			if (isset($this->class)) 
				$stmnt->setFetchMode(PDO::FETCH_CLASS,$this->class);
			else $stmnt->setFetchMode(PDO::FETCH_OBJ);
			return $stmnt;
		} else {
			_F_EXTENSION_DATA_::_f_error_info_($this->db->connection,$query,$stmnt);
			return false;
		}
	}
	
	public function count() {
		if ($this->_f_count_ === null) {
			$query = ' FROM '.$this->query['from'].$this->where.$this->limit;
			$select = strtoupper($this->query['select']);
			if (preg_match('/(DISTINCT\s)|(\sAS\s)|,/ims',$select)) {
				$query = 'SELECT COUNT(*) AS _f_count_ FROM (SELECT '.
					$this->query['select'].$query.') AS _f_count_subquery_';
			} else {
				$query = 'SELECT COUNT('.$this->query['select'].
					') AS _f_count_'.$query;					
			}
			$stmnt = $this->db->connection->prepare($query);
			if ($stmnt->execute($this->params)) {
				$result = $stmnt->fetch(PDO::FETCH_ASSOC);
				$this->_f_count_ = $result['_f_count_'];
			} else {
				_F_EXTENSION_DATA_::_f_error_info_($this->db->connection,$query,$stmnt);
				return false;
			}
		}
		return $this->_f_count_;
	}
	
	public function _f_get_where_() {
		if ($this->_f_where_ === null) {
			if (isset($this->query['where'])) {
				$this->_f_where_ = ' WHERE '.$this->query['where'];
			} else {
				$this->_f_where_ = '';
			}
		}
		return $this->_f_where_;
	}

	public function _f_get_order_() {
		if ($this->_f_order_ === null) {
			if (isset($this->query['order'])) {
				$this->_f_order_ = ' ORDER BY '.$this->query['order'];
			} else {
				$this->_f_order_ = '';
			}
		}
		return $this->_f_order_;
	}

	public function _f_get_limit_() {
		if ($this->_f_limit_ === null) {
			if (isset($this->query['limit'])) {
				$this->_f_limit_ = ' LIMIT '.(isset($this->query['first']) ? 
					$this->query['first'] : '0').','.$this->query['limit'];
			} else {
				$this->_f_limit_ = '';
			}
		}
		return $this->_f_limit_;
	}
	
	public function _f_get_sql_() {
		if ($this->_f_sql_ === null) {
			$this->_f_sql_ = 'SELECT '.$this->query['select'].
				' FROM '.$this->query['from'].
				$this->where.$this->order.$this->limit;
		}
		return $this->_f_sql_;
	}
	
	public function select() {
		return new _F_EXTENSION_DATA_SELECT_($this->db,
			$this->query,$this->params,$this->class);
	}
	
}

